/*
 * @Description  : 工具库
 * @Autor        : yanwang
 * @CreateDate   : 2023-05-22 16:39:20
 * @LastEditors  : yanwang
 * @LastEditTime : 2023-05-26 15:26:06
 */
const ora = require('ora');
const path = require('path');
const fs = require('fs-extra');

/**
 * 封装loading
 * @param {*} fn
 * @param {*} message
 * @returns
 */
const waitFnloading = (fn, message = 'loading...') => async (...args) => {
  const spinner = ora(message);
  spinner.start();
  const result = await fn(...args);
  spinner.succeed();
  return result;
};

/**
 * 等待
 * @param {*} time
 * @returns
 */
const sleep = (time = 1000) => new Promise((resolve) => {
  setTimeout(() => {
    resolve(null);
  }, time);
});

/**
 * 重调函数
 * @param {*} fn
 * @param {*} times
 */
const retry = (fn, n, time = 2) => (...args) => new Promise(async (resolve, reject) => {
  let count = 0;
  (async function execuate() {
    count++;
    if (count >= n) {
      count = 0;
      // eslint-disable-next-line prefer-promise-reject-errors
      reject('\n下载次数超过限制\n');
    }

    try {
      const res = await fn(...args);
      count = 0;
      resolve(res);
    } catch (e) {
      console.log(`\n下载失败,${time}s后重试...\n`);
      await sleep(time);
      execuate();
    }
  }());
});

/**
 *  修改package.json
 * @param {*} dirpath
 * @param {*} data
 */
const updatePackage = async (dirpath, data) => {
  const filename = path.join(dirpath, 'package.json');
  try {
    await fs.ensureFile(filename);
    let packageJson = await fs.readFile(filename);
    packageJson = JSON.parse(packageJson.toString());
    packageJson = { ...packageJson, ...data };
    packageJson = JSON.stringify(packageJson, null, '\t');
    await fs.writeFile(filename, packageJson);
  } catch (err) {
    console.error('\npackage.json文件操作失败!\n');
    throw err;
  }
};

/**
 * 两种引入方式
 * @param {*} absPath
 * @returns
 */
const betterRequire = (absPath) => {
  const module = require(absPath);
  return module.default || module;
};

const cleanArgs = (cmd) => {
  const args = {};
  cmd.options.forEach((o) => {
    const key = o.long.slice(2);
    if (cmd[key]) args[key] = cmd[key];
  });
};

module.exports = {
  waitFnloading,
  sleep,
  retry,
  updatePackage,
  betterRequire,
};
